package socketmvc.core.packets;

import org.tio.core.ChannelContext;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import socketmvc.core.packets.basic.impl.JsonTextBody;
import socketmvc.core.packets.basic.impl.JsonSimplePacket;

import java.util.HashMap;
import java.util.Map;

public class WsHandshakePacket extends JsonSimplePacket {

    // 握手标识 0代表正在握手，1代表已经握手完成
    private Byte handshakeFlag;
    private final HttpRequest httpRequest;

    public WsHandshakePacket(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) {
        super(new JsonTextBody());
        Map<String, Object[]> params = httpRequest.getParams();
        Map<String,Object> body = new HashMap<>();
        params.forEach((k,v)->{
           if(v.length == 1){
               body.put(k,v[0]);
           } else if (v.length > 1) {
               body.put(k,v);
           }
        });
        this.textBody.setBody(body);
        Map<String, String> headers = httpRequest.getHeaders();
        headers.forEach((k,v)-> this.textBody.setHeader(k,v));
        this.httpRequest = httpRequest;
        this.setHandshakeFlag((byte)0);
    }

    public Byte getHandshakeFlag() {
        return handshakeFlag;
    }

    public boolean shakingHands(){
        return handshakeFlag == 0;
    }

    public void setHandshakeFlag(Byte handshakeFlag) {
        if (handshakeFlag < 0 || handshakeFlag > 1){
            throw new IllegalArgumentException("参数异常，handshakeFlag取值只能是 1 或者 0 ;");
        }
        if (handshakeFlag == 0){
            this.setCommand("/@ws-handshake");
        }else {
            this.setCommand("/@ws-handshake-after");
        }
        this.handshakeFlag = handshakeFlag;
    }

    public Map<String,String> getRequestHeaders(){
       return httpRequest.getHeaders();
    }

    public String getRequestHeader(String key){
        return httpRequest.getHeader(key);
    }

    public String getRequestParam(String key){
        return httpRequest.getParam(key);
    }

    @Override
    public String getCommand() {
        return super.getCommand();
    }

    @Override
    public String getResponseKey() {
        return "";
    }
}
